<template>
  <vxe-grid ref='xGrid' v-bind="gridOptions"
    @checkbox-change="checkboxChange"
    @checkbox-all="checkboxAll"
    @checkbox-range-change="checkboxRangeChange">
      <template #form>
        <slot name="form"></slot>
      </template>

      <!-- left -->
      <template #toolbar_buttons>
        <slot name="defaultButtons"></slot>

        <Divider type="vertical"/>
        <span v-for="(v, i) in buttons.topLeft" :key="`i-${i}`">
          <Popconfirm v-if="v.tip"
            placement="bottom"
            :title="v.tipContent"
            cancel-text="取消"
            :disabled="batchDeleteDisabled"
            @confirm="handleCall(v.func)">
            <a :class="{disabled:batchDeleteDisabled}">{{v.name}}</a>
          </Popconfirm>
          <a v-else @click="handleCall(v.func)">{{v.name}}</a>
          <Divider type="vertical"/>
        </span>


        <!-- <Popconfirm
          placement="bottom"
          title="警告: 【重新装载】所有的系统API策略?"
          ok-text="确定"
          cancel-text="取消"
          @confirm="handleReloadPolicy">
          <vxe-button icon="vxe-icon--menu" status="primary" :loading="reloadPolicyLoading">装载策略</vxe-button>
        </Popconfirm> -->

        <!-- <Popconfirm
          placement="bottom"
          title="提示: 选择是否记录日志?"
          ok-text="记录"
          cancel-text="不记录"
          :disabled="batchDeleteDisabled"
          @confirm="handlePolicyLog(true)"
          @cancel="handlePolicyLog(false)">
          <vxe-button icon="vxe-icon--edit-outline" status="info" :disabled="batchDeleteDisabled">日志埋点</vxe-button>
        </Popconfirm> -->
      </template>

      <!-- operate -->
      <template #operate="{ row }">
      <Divider type="vertical"/>
      <span v-for="(v, i) in buttons.inner" :key="`i-${i}`">
          <Popconfirm v-if="v.tip"
            placement="bottom"
            :title="v.tipContent"
            cancel-text="取消"
            @confirm="handleCall(v.func, {row: row})">
            <a>{{v.name}}</a>
          </Popconfirm>
          <a v-else @click="handleCall(v.func, {row: row})">{{v.name}}</a>
          <Divider type="vertical"/>
        </span>

      <!-- <a v-for="(v, i) in buttons.inner" :key="`i-${i}`">{{v.name}}<Divider type="vertical"/></a>
      <vxe-button status="primary" icon="vxe-icon--edit-outline" title="编辑" circle
                    @click="handleCall('edit', row)"></vxe-button>
        <Popconfirm
          placement="topRight"
          title="慎重！确定删除【单行数据】吗?"
          ok-text="删除"
          cancel-text="取消"
          @confirm="handleDelete(row?.id)">
          <vxe-button status="danger" icon="vxe-icon--close" title="删除" circle></vxe-button>
        </Popconfirm> -->
      </template>

  </vxe-grid>
</template>
<script lang="ts" name="XGrid" setup>
import {reactive, ref, watchEffect, computed,} from 'vue';
import {useRoute} from 'vue-router';
import {VxeTablePropTypes, VxeGridPropTypes, VxeGridProps} from 'vxe-table';
import {Popconfirm, Divider} from 'ant-design-vue';
import { defHttp } from '/@/utils/http/axios';
import { toLower } from 'lodash-es';
// import { usePermission } from '/@/hooks/web/usePermission';

// const { hasPermission } = usePermission();
const route = useRoute();
let prefix = '/' + toLower(route.name?.toString())

const buttons = reactive({
  topLeft: [] as any[],
  topRight: [] as any [],
  inner: [] as any[],
})
// console.log(route)
let {buttonList} = route.meta
if (buttonList) {
  buttons.topLeft = buttonList.filter(e => e.place === 0)
  buttons.topRight = buttonList.filter(e => e.place === 1)
  buttons.inner = buttonList.filter(e => e.place === 2)
}

const props = defineProps({
  url: { type: String, default: '' },
  size: { type: String, default: 'mini' },
  isTree: { type: Boolean, default: false },
  columns: { type: Array, default: () => [] },
  height: { type: Number, default: window.innerHeight - 113 },
  border: {type: [String, Boolean], default: 'full'}, // default | full | outer | inner | none
  line: {type: Boolean, default: true},
  stripe: {type: Boolean, default: true},
  showOverflow: {type: [String, Boolean], default: 'tooltip'}, // 'ellipsis' | 'title' | 'tooltip'
  printTop: { type: String, default: '' },
  printBottom: { type: String, default: '' },
  printStyle: { type: String, default: '' },
})

const xGrid = ref()

const topRight = reactive({
    // refresh: true,
    import: false,
    export: false,
    print: true,
    zoom: true,
    custom: true,
})
const gridOptions = reactive<VxeGridProps>({
  border: props.border as VxeTablePropTypes.Border,
  resizable: true,
  showHeaderOverflow: true,
  showOverflow: props.showOverflow as VxeTablePropTypes.ShowOverflow,
  highlightHoverRow: true,
  keepSource: true,
  id: 'xGrid_' + new Date().getTime(),
  stripe: props.stripe,
  height: props.height,
  size: props.size as VxeTablePropTypes.Size,
  rowId: 'id',
  columns: props.columns as VxeGridPropTypes.Columns,
  columnConfig: {
    useKey: true,
    isCurrent: true,
    isHover: true,
  },
  rowConfig: {
    useKey: true,
    isCurrent: true,
    isHover: false,
  },
  customConfig: {
    storage: true,
  },
  printConfig: {
    sheetName: '',
    mode: 'selected',
    style: props.printStyle,
    modes: ['current', 'selected', 'all'],
    columnFilterMethod: ({ column, $columnIndex }) => {
      return column.type !== 'checkbox';
    },
    beforePrintMethod: ({ content, options }) => {
      let result = props.printTop + content + props.printBottom;
      // result = `<div style="width:100%">` + result + `</div>`
      return result;
    }
  },
  sortConfig: {
    trigger: 'cell',
    remote: false
  },
  filterConfig: {
    remote: false
  },
  pagerConfig: {
    total: 0,
    currentPage: 1,
    pageSize: 50,
    pageSizes: [50, 100, 200, 500, 1000],
    layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'],
    border: true,
    background: true,
    perfect: true,
  },
  toolbarConfig: {
    refresh: true,
    import: topRight.import,
    export: topRight.export,
    print: topRight.print,
    zoom: topRight.zoom,
    custom: topRight.custom,
    slots: {
      buttons: 'toolbar_buttons',
    },
  },
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all'],
  },
  checkboxConfig: {
    // labelField: 'id',
    reserve: false,
    highlight: true,
    range: true,
    trigger: 'cell',
  },
  proxyConfig: {
    ajax: {
      query({ page, sort, sorts, filters, form }) {
        batchDeleteDisabled.value = true
        return defHttp.get<any>({ url: url.value, params: page });
      },
      queryAll({ page, sort, sorts, filters, form }) {
        return defHttp.get<any>({ url: prefix + '/list', params: page });
      }
    }
  },
});
const url = computed(() => {
  let path = ''
  if (props.url) {
    path = props.url;
  } else {
    path = props.isTree ? (prefix + '/list') : (prefix + '/table');
  }
  return path;
})
watchEffect(() => {
  if (props.isTree) {
    gridOptions.treeConfig = {
      rowField: 'id',
      trigger: 'cell',
      line: props.line,
      expandAll: true,
    }
    gridOptions!.checkboxConfig!.range = false;
    delete gridOptions.pagerConfig
  }
})

const reload = () => {
  batchDeleteDisabled.value = true
  defHttp.get<any>({ url: url.value,}).then(dd => {
    if (props.isTree) {
      xGrid.value.loadData(dd)
    } else {
      xGrid.value.loadData(dd?.result)
      let {pager} = xGrid.value.getProxyInfo()
      pager.total = dd?.page?.total
    }
  })
}

const handleDelete = (...params: number[]) => {
  if (params.length > 0) {
    defHttp.delete({url: prefix, data: params}).then(() => {
      batchDeleteDisabled.value = true
      reload()
    })
  }
}
const handleBatchDelete = () => {
  let checkedList = xGrid.value.getCheckboxRecords(true).map(e => e.id)
  handleDelete(...checkedList)
}

const batchDeleteDisabled = ref(true)
const checkboxChange = ({ checked, row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }) => {
  batchDeleteDisabled.value = !(xGrid.value.getCheckboxRecords(true).length > 0)
}
const checkboxAll = ({ checked, $event }) => {
  batchDeleteDisabled.value = !checked
}
const checkboxRangeChange = ({ $event }) => {
  batchDeleteDisabled.value = !(xGrid.value.getCheckboxRecords(true).length > 0)
}

const emits = defineEmits(['create', 'edit']);
const funcMap: Map<String, Function> = new Map([
  ['create', () => {
    emits('create')
  }],
  ['edit', (params:any) => {
    emits('edit', params.row)
  }],
  ['delete', (params:any) => handleDelete(params.row?.id)],
  ['batchDelete', handleBatchDelete],
]);
// 调用
const handleCall = (funcName:string, params?:HandlerParams) => {
  if (funcName !== '-') {
    let func = funcMap.get(funcName)
    if (func) {
      if(params) func(params)
      else func()
    }
  }
}

defineExpose({
  reload,
})
</script>
<style scoped>
.disabled {
  pointer-events: none;
  opacity: .5;
  -moz-opacity: .5;
  /* 黑白色 */
  -webkit-filter: grayscale(100%); /* Chrome, Safari, Opera */
  filter: grayscale(100%);
}
</style>
